<?php
class Validator{

    public static $MD5KEY = 'Fw8LK@A3aFDS#OM1qQC*GbY';
    const DEFAULT_EXPIRE = 86400;// TOKEN默认过期时间（1天）

	public static function checkBankcard($card) {
		$len = strlen($card);

		if (!is_numeric($card) || $len < 10 || $len > 19) {
			return false;
		}

		return true;
	}

	public static function checkIdcard($idcard)
	{
		$regidcard = "/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/i";
		return preg_match($regidcard, $idcard) == 1 ? true : false;
	}

	public static function checkImg($imgUrl){
        return preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $imgUrl) ==1 ? true : false;
    }

	public static function checkUsername($username, $checkphone = true){

	    if (self::checkPhone($username)) {
	        return $checkphone ? false : true;
        }

		$username = trim($username);
		$len = mb_strlen($username);
		if($len < 4 || $len>16){
			return false;
		}
		return preg_match('/(^[0-9]+[a-zA-Z]+[0-9a-zA-Z]*$)|(^[a-zA-Z]+[0-9a-zA-Z]*$)/', $username) === 1;
	}
	
	public static function checkPassword($password){
		$password = trim($password);
		return (empty($password) || mb_strlen($password, 'utf-8') < 6 || mb_strlen($password, 'utf-8') > 20) ? false : true;
	}

	public static function checkRealname($realname) {
		$realname = trim($realname);
		return (empty($realname) || mb_strlen($realname, 'utf-8') < 2 || mb_strlen($realname, 'utf-8') > 10) ? false : true;
	}

	public static function checkPhone($phone){
// 		$regex = '/^1((3[0-9])|(4[57])|(5[012356789])|(8[02356789]))[0-9]{8}$/';
		$regex = '/^1((3[0-9])|(4[0-9])|(5[0-9])|(6[0-9])|(7[0-9])|(8[0-9])|(9[0-9]))[0-9]{8}$/';
		return preg_match($regex, $phone) == 1 ? true : false;
	}
	
	/**
	 * 
	 * @param int $money 单位分
	 */
	public static function checkMoney($money){
		$regex = '/^[1-9]\d*00$/';
		return preg_match($regex, $money) == 1 ? true : false;
	}
	
	/**
	 *
	 * @param int $coin 单位
	 */
	public static function checkCoin($coin){
		if(intval($coin) < 10){
			return false;
		}
		$regex = '/^[1-9]\d*0$/';
		return preg_match($regex, $coin) == 1 ? true : false;
	}

	/**
	 * 验证身份证
	 * @param string $num
	 */
	public static function validateIdcard($id){
		$id = strtoupper($id);
		$regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";

		$arr_split = array();
		if(! preg_match($regx, $id)){
			return false;
		}

		if(15 == strlen($id)){
			$regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

			@preg_match($regx, $id, $arr_split);
			// 检查生日日期是否正确
			$dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
			if(! strtotime($dtm_birth)){
				return false;
			}else{
				return true;
			}
		}else{
			$regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
			@preg_match($regx, $id, $arr_split);
			$dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
			if(! strtotime($dtm_birth)){
				return false;
			}else{
				// 检验18位身份证的校验码是否正确。
				// 校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
				$arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
				$arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');

				$sign = 0;
				for($i = 0; $i < 17; $i ++){
					$b = (int)$id{$i};
					$w = $arr_int[$i];
					$sign += $b * $w;
				}

				$n = $sign % 11;
				$val_num = $arr_ch[$n];

				if($val_num != substr($id, 17, 1)){
					return false;
				}else{
					return true;
				}
			}
		}
	}


    /**
     * 验证是否正确身份证
     * @param string $num
     */
    public static function isValidateIdcard($id){
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";

        if(! preg_match($regx, $id)){
            return false;
        }
        if(15 == strlen($id)) {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
        }else{
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        }
        if(! preg_match($regx, $id)){
            return false;
        }else{
            return true;
        }
    }


    //未成年人年龄段计算,未实名或格式错误返回0
    public static function idIsAdults($idcard) {
        if(!self::isValidateIdcard($idcard) ){
            return 0;
        }

        $date = substr($idcard, 6, 8);
        $time = intval(strtotime($date));


        if(strtotime('+18 years', $time) > time()){  //小于18岁
            return 1;
        }elseif (strtotime('+18 years', $time) <= time() && strtotime('+24 years', $time) > time()){     //大于18岁小于23岁
            return 2;
        }elseif (strtotime('+24 years', $time) <= time() && strtotime('+31 years', $time) > time()){     //大于24岁小于30岁
            return 3;
        }elseif(strtotime('+31 years', $time) <= time() && strtotime('+41 years', $time) > time()){    //大于31岁小于40岁
            return 4;
        }elseif(strtotime('+41 years', $time) <= time() && strtotime('+50 years', $time) > time()){    //大于41岁小于49岁
            return 5;
        }else{  //大于50岁
            return 6;
        }
    }

    /**
     * 检查用户token
     * @param int $uid
     * @param string $token
     * @return boolean
     */
    public static function checkToken($uid, $token, $expire = null){
        if ($uid < 1){
            return false;
        }
        $expire = !is_null($expire)&&$expire>0?intval($expire):self::DEFAULT_EXPIRE;

        $dec_strarr = str_split($token, 4);
        $parsenum = count($dec_strarr);
        if ($parsenum < 10){
            return false;
        }

        $dec_timestr = '';
        $dec_sign = '';
        //==========解析时间==========
        for ($j = 0; $j < $parsenum; ++$j){
            if ($j < 10){
                $pos = $uid % ($j + 1);
                if ($pos == 0){
                    $dec_timestr .= substr($dec_strarr[$j], -1);
                    $dec_sign .= substr($dec_strarr[$j], 0, 3);
                }else{
                    $dec_timestr .= substr($dec_strarr[$j], 0, 1);
                    $dec_sign .= substr($dec_strarr[$j], -3);
                }
            }else{
                $dec_sign .= $dec_strarr[$j];
            }
        }

        if (!is_numeric($dec_timestr)){
            return false;
        }

        if (time() - $dec_timestr > $expire){
            return false;
        }

        $str = md5(self::$MD5KEY . $uid . $dec_timestr);
        $str2 = md5($str);

        $strarr = array();
        for ($i = 0; $i < strlen($str); ++$i){
            $strarr[] = $str[$i];
            if ($i > 0 && $uid % $i == 0){
                $strarr[] .= $str2[$i];
            }
        }
        $sign = implode('', $strarr);

        return $dec_sign===$sign;
    }

    /**
     * 生成用户token
     * @param int $uid
     * @param string $day
     */
    public static function token($uid) {
        $time = time();

        $str = md5(self::$MD5KEY . $uid . $time);
        $str2 = md5($str);

        $strarr = array();
        for ($i = 0; $i < strlen($str); ++$i){
            $strarr[] = $str[$i];
            if ($i > 0 && $uid % $i == 0){
                $strarr[] .= $str2[$i];
            }
        }
        $sign = implode('', $strarr);

        //==========插入时间==========
        $t1 = str_split($sign, 3);
        $timestr = strval($time);

        $uposarr = array();
        for ($j = 0; $j < 10; ++$j){
            $pos = $uid % ($j + 1);
            if ($pos == 0){
                $t1[$j] = $t1[$j] . $timestr[$j];
            }else{
                $t1[$j] = $timestr[$j] . $t1[$j];
            }
        }

        $token = implode('', $t1);
        return $token;
    }
}